<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2014 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: Tuolaji <479923197@qq.com>
// +----------------------------------------------------------------------
namespace Admin\Controller;

use Common\Controller\AdminbaseController;

class NewsController extends AdminbaseController {
    
	protected $news_model;
	protected $newscat_model;
	
	function _initialize() {
		parent::_initialize();
		$this->news_model = D("Common/News");
		$this->newscat_model = D("Common/NewsCat");
	}
	
	// 后台文章管理列表
	public function index(){
        $cid=I('request.news_cat_id',0,'intval');
        if(!empty($cid)){
            $where['n.news_cat_id']=$cid;
        }
        $start_time=I('request.start_time');
        if(!empty($start_time)){
            $where['news_date']=array(
                array('EGT',$start_time)
            );
        }

        $end_time=I('request.end_time');
        if(!empty($end_time)){
            if(empty($where['news_date'])){
                $where['news_date']=array();
            }
            array_push($where['news_date'], array('ELT',$end_time));
        }
        $keyword=I('request.keyword');
        if(!empty($keyword)){
            $where['news_title']=array('like',"%$keyword%");
        }

        $count=$this->news_model->count();

        $page = $this->page($count, 20);

        $this->news_model
            ->alias("n")
            ->join("__USERS__ c ON n.news_author = c.id")
            ->where($where)
            ->limit($page->firstRow , $page->listRows)
            ->order("n.news_date DESC");
        if(empty($cid)){
            $this->news_model->field('n.*,c.user_login,c.user_nicename');
        }else{
            $this->news_model->field('n.*,c.user_login,c.user_nicename');
        }
        $posts=$this->news_model->order('n.listorder asc')->select();
        $p = I('p') == '' ? 1 : I('p');
        $this->assign("page", $page->show('Admin'));
        $this->assign("p", $p);
        $this->assign("news_cat_id", $cid);
        $this->assign("formget",array_merge($_GET,$_POST));
        $this->assign("posts",$posts);

        //获取分类
        $cat = $this->newscat_model->select();
        $this->assign('cat',$cat);
		$this->display();
	}
	
	// 文章添加
	public function add(){
        $cat = $this->newscat_model->select();
        $this->assign('cat',$cat);
		$this->display();
	}
	
	// 文章添加提交
	public function add_post(){
		if (IS_POST) {
			$_POST['smeta']['thumb'] = sp_asset_relative_url($_POST['smeta']['thumb']);
			$_POST['post']['news_modified']=date("Y-m-d H:i:s",time());
			$_POST['post']['news_author']=get_current_admin_id();
			$article=I("post.post");
            $article['smeta']=json_encode($_POST['smeta']);
			$article['news_content']=htmlspecialchars_decode($article['news_content']);
			$result=$this->news_model->add($article);
			if ($result) {
				$this->success("添加成功！");
			} else {
				$this->error("添加失败！");
			}
		}
	}
	
	// 文章编辑
	public function edit(){
		$id=  I("get.id",0,'intval');
        $cat = $this->newscat_model->select();
		$news=$this->news_model->where("id=$id")->find();
        $this->assign("smeta",json_decode($news['smeta'],true));
        $p = I('p') == '' ? 1 : I('p');
		$this->assign("news",$news);
        $this->assign('cat',$cat);
        $this->assign('p',$p);
		$this->display();
	}
	
	// 文章编辑提交
	public function edit_post(){
		if (IS_POST) {
			$_POST['smeta']['thumb'] = sp_asset_relative_url($_POST['smeta']['thumb']);
			unset($_POST['post']['news_author']);
			$_POST['post']['news_modified']=date("Y-m-d H:i:s",time());
			$article=I("post.post");
            $article['smeta']=json_encode($_POST['smeta']);
			$article['news_content']=htmlspecialchars_decode($article['news_content']);
			$result=$this->news_model->save($article);
			if ($result!==false) {
				$this->success("保存成功！");
			} else {
				$this->error("保存失败！");
			}
		}
	}
	
	// 文章排序
	public function listorders() {
		$status = parent::_listorders($this->news_model);
		if ($status) {
			$this->success("排序更新成功！");
		} else {
			$this->error("排序更新失败！");
		}
	}
	
	/**
	 * 文章列表处理方法,根据不同条件显示不同的列表
	 * @param array $where 查询条件
	 */
	private function _lists($where=array()){
		$cid=I('request.news_cat_id',0,'intval');

//		$where['news_type']=array(array('eq',1),array('exp','IS NULL'),'OR');
		
		if(!empty($cid)){
		    $where['b.cid']=$cid;
			$term=$this->newscat_model->where(array('cid'=>$cid))->find();
			$this->assign("term",$term);
		}
		
		$start_time=I('request.start_time');
		if(!empty($start_time)){
		    $where['news_date']=array(
		        array('EGT',$start_time)
		    );
		}
		
		$end_time=I('request.end_time');
		if(!empty($end_time)){
		    if(empty($where['news_date'])){
		        $where['news_date']=array();
		    }
		    array_push($where['news_date'], array('ELT',$end_time));
		}
		
		$keyword=I('request.keyword');
		if(!empty($keyword)){
		    $where['news_title']=array('like',"%$keyword%");
		}
			
		$this->news_model
		->alias("a")
		->where($where);
		
		if(!empty($term_id)){
		    $this->news_model->join("__TERM_RELATIONSHIPS__ b ON a.id = b.object_id");
		}
		
		$count=$this->news_model->count();
			
		$page = $this->page($count, 20);
			
		$this->news_model
		->alias("a")
		->join("__USERS__ c ON a.news_author = c.id")
		->where($where)
		->limit($page->firstRow , $page->listRows)
		->order("a.news_date DESC");
		if(empty($term_id)){
		    $this->news_model->field('a.*,c.user_login,c.user_nicename');
		}else{
		    $this->news_model->field('a.*,c.user_login,c.user_nicename,b.listorder,b.tid');
		    $this->news_model->join("__TERM_RELATIONSHIPS__ b ON a.id = b.object_id");
		}
		$posts=$this->news_model->select();
		
		$this->assign("page", $page->show('Admin'));
		$this->assign("news_cat_id", $cid);
		$this->assign("formget",array_merge($_GET,$_POST));
		$this->assign("posts",$posts);
	}
	
	// 获取文章分类树结构 select 形式
	private function _getTree(){
		$term_id=empty($_REQUEST['term'])?0:intval($_REQUEST['term']);
		$result = $this->newscat_model->select();
		
		$tree = new \Tree();
		$tree->icon = array('&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
		$tree->nbsp = '&nbsp;&nbsp;&nbsp;';
		foreach ($result as $r) {
			$r['str_manage'] = '<a href="' . U("AdminTerm/add", array("parent" => $r['term_id'])) . '">添加子类</a> | <a href="' . U("AdminTerm/edit", array("id" => $r['term_id'])) . '">修改</a> | <a class="js-ajax-delete" href="' . U("AdminTerm/delete", array("id" => $r['term_id'])) . '">删除</a> ';
			$r['visit'] = "<a href='#'>访问</a>";
			$r['taxonomys'] = $this->taxonomys[$r['taxonomy']];
			$r['id']=$r['term_id'];
			$r['parentid']=$r['parent'];
			$r['selected']=$term_id==$r['term_id']?"selected":"";
			$array[] = $r;
		}
		
		$tree->init($array);
		$str="<option value='\$id' \$selected>\$spacer\$name</option>";
		$taxonomys = $tree->get_tree(0, $str);
		$this->assign("taxonomys", $taxonomys);
	}
	
	// 获取文章分类树结构 
	private function _getTermTree($term=array()){
		$result = $this->newscat_model->select();
		
		$tree = new \Tree();
		$tree->icon = array('&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
		$tree->nbsp = '&nbsp;&nbsp;&nbsp;';
		foreach ($result as $r) {
			$r['str_manage'] = '<a href="' . U("AdminTerm/add", array("parent" => $r['term_id'])) . '">添加子类</a> | <a href="' . U("AdminTerm/edit", array("id" => $r['term_id'])) . '">修改</a> | <a class="js-ajax-delete" href="' . U("AdminTerm/delete", array("id" => $r['term_id'])) . '">删除</a> ';
			$r['visit'] = "<a href='#'>访问</a>";
			$r['taxonomys'] = $this->taxonomys[$r['taxonomy']];
			$r['id']=$r['term_id'];
			$r['parentid']=$r['parent'];
			$r['selected']=in_array($r['term_id'], $term)?"selected":"";
			$r['checked'] =in_array($r['term_id'], $term)?"checked":"";
			$array[] = $r;
		}
		
		$tree->init($array);
		$str="<option value='\$id' \$selected>\$spacer\$name</option>";
		$taxonomys = $tree->get_tree(0, $str);
		$this->assign("taxonomys", $taxonomys);
	}
	
	// 文章删除
	public function delete(){
		if(isset($_GET['id'])){
			$id = I("get.id",0,'intval');
			if ($this->news_model->where(array('id'=>$id))->delete() !==false) {
				$this->success("删除成功！");
			} else {
				$this->error("删除失败！");
			}
		}
		
		if(isset($_POST['ids'])){
			$ids = I('post.ids/a');
			
			if ($this->news_model->where(array('id'=>array('in',$ids)))->delete()!==false) {
				$this->success("删除成功！");
			} else {
				$this->error("删除失败！");
			}
		}
	}
	
	// 文章回收站列表
	public function recyclebin(){
		$this->_lists(array('news_status'=>array('eq',3)));
		$this->_getTree();
		$this->display();
	}
	
	// 清除已经删除的文章
	public function clean(){
		if(isset($_POST['ids'])){
			$ids = I('post.ids/a');
			$ids = array_map('intval', $ids);
			$status=$this->news_model->where(array("id"=>array('in',$ids),'news_status'=>3))->delete();
			$this->term_relationships_model->where(array('object_id'=>array('in',$ids)))->delete();
			if ($status!==false) {
				$this->success("删除成功！");
			} else {
				$this->error("删除失败！");
			}
		}else{
			if(isset($_GET['id'])){
				$id = I("get.id",0,'intval');
				$status=$this->news_model->where(array("id"=>$id,'news_status'=>3))->delete();
				$this->term_relationships_model->where(array('object_id'=>$id))->delete();
				
				if ($status!==false) {
					$this->success("删除成功！");
				} else {
					$this->error("删除失败！");
				}
			}
		}
	}
	
	// 文章还原
	public function restore(){
		if(isset($_GET['id'])){
			$id = I("get.id",0,'intval');
			if ($this->news_model->where(array("id"=>$id,'news_status'=>3))->save(array("news_status"=>"1"))) {
				$this->success("还原成功！");
			} else {
				$this->error("还原失败！");
			}
		}
	}
}